from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium import webdriver
import pyautogui as pi
import xlrd
import time
class User:
    def __init__(self,Account,Name,FullUr):
        self.__Account = Account
        self.__Password = "123456"
        self.__FullUrl=GetFullUrl
        self.__Name = Name
    def getAccount(self):
        return  self.__Account
    def getPassword(self):
        return self.__Password
    def getName(self):
        return self.__Name
    def getFullUrl(self):
        return self.__FullUrl
    def getDaili(self):
        begin_str = self.getAccount()[0:2]
        if(begin_str == 'xz'):
            return True
        else:
            return False

filepath = './custom.xls'
workbook =  xlrd.open_workbook(filepath)
worksheet1 = workbook.sheet_by_name('sheet1')
def GetSetting():
    settings = []
    temp1 = ""
    for i in range(6):
        temp1 = str(worksheet1.cell_value(1,i))
        settings.append(temp1) 
    return settings
def GetCustomValue(sheetName,number,cel1,cel2):
    worksheet2=workbook.sheet_by_name(sheetName)
    list1 = []
    for i in range (number):
        xpath1 = str(worksheet2.cell_value(i,cel1))
        value1 = str(worksheet2.cell_value(i,cel2))
        list1.append([xpath1,value1])
    return list1
def SetUrl(s1):
    begin_url = "http://"
    end_url = '/member/login/executeLogin.htm'
    s =  begin_url + s1 + end_url 
    return s
def getValue(worksheet1,cel1,row1):
    return worksheet1.cell_value(cel1,row1)

def GetFullUrl():
    if settings[2].upper() == 'CUSTOM':
        fullUrl = SetUrl(getValue(worksheet1,2,2))
    elif settings[2].upper() == "LOCAL":
        fullUrl = SetUrl('localhost:6850')
    elif settings[2].upper() == "UAT":
        fullUrl = SetUrl('61.187.51.25:8084')
    elif settings[2].upper() == "DEV":
        fullUrl = SetUrl('61.187.51.25:8800')
    elif settings[2].upper() == "PROD":
        fullUrl = SetUrl("www.holdcg.com")
    else:
        fullUrl = "http://www.baidu.com"
    return fullUrl
def getTimeStrip():
    #return time.strftime("%Y{}%m{}%d{} %H{}%M{}%S{}",time.localtime()).format('年','月','日','时','分','秒')
    return time.strftime("%Y{}%m{}%d{}-%H{}%M{}",time.localtime()).format('年','月','日','点','分')
def pmlogin(driver, person):
    driver.get(GetFullUrl())
    locationLogin = (By.LINK_TEXT, '立即登录')
    try:
        WebDriverWait(driver, 20, 0, 5).until(presence_of_element_located(locationLogin))
    except:
        print('登录界面加载失败----')
    driver.find_element(By.ID, 'username').send_keys(person.getAccount())
    driver.find_element(By.ID, 'xstr').send_keys(person.getPassword())
    driver.find_element(By.LINK_TEXT, '立即登录').click()
# find xpath rows number
def numberOfXpath(row,sheetname):
    i = 0
    temp = getValueOfRowCell(sheetname,i,row)
    flag = (temp!="")
    print(flag)
    while flag:
        i = i + 1
        temp = getValueOfRowCell(sheetname,i,row)
        flag = (temp!="") 
    return i
def getValueOfRowCell(sheetname,row,cell):
    try:
        worksheet_v = workbook.sheet_by_name(sheetname) 
        str1 = worksheet_v.cell_value(int(row),int(cell))
    except:
        print("out of list in this row")
        return ""
    return str1
def fileMethod(value1):
    #pi.confirm("ready?")
    time.sleep(4)
    pi.hotkey('ctrlleft','f4')
    for i in range(6):
        time.sleep(1)
        pi.press("tab")
    #v1 = value1[1:-1]
    pi.write(value1,interval=0)
    time.sleep(1)
    pi.press('enter')
    time.sleep(1)
    pi.hotkey("alt","o")
def timeMethod(value1):
    sec = int(value1)
    time.sleep(sec)
def customInput(driver,wins,list1):
    xpath1 = list1[0]
    value1 = list1[1]
    if xpath1 == 'file':
        fileMethod(value1)
    elif xpath1 == 'time':
        timeMethod(value1)
    elif xpath1 == 'switch':
        driver.switch_to.window(wins[-1])
    #elif xpath1 == 'js':
        #js = 'document.getElementById("fileIdPdf_UploaderBtn").click();'
        #driver.execute_script(js)
    else:
        element1 = (By.XPATH,xpath1)
        try:
            WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(element1))
        except:
            print("the element is not found:"+xpath1)
        try:
            WebDriverWait(driver, 20, 0, 5).until(presence_of_element_located(element1))
        except:
            print("there is no such a element:"+xpath1)
        if(value1 == ''):
            try:
                driver.find_element(By.XPATH,xpath1).click()
            except:
                try:
                    driver.find_elemnet(By.XPATH,xpath1).send_keys(Keys.ENTER)
                except:
                    print("send_keys:enter fail")
                print("click - error:"+xpath1)
        else:
            try:
                driver.find_element(By.XPATH,xpath1).send_keys(value1)
            except:
                print("click - error:"+xpath1)

if __name__=="__main__":
    """
    0 xz18073180118 1 田甜 2 local 3 custom 4 1-1 5 1-2 
    """
    settings = GetSetting()
    user = User(settings[0],settings[1],GetFullUrl())
    cel1 = int(settings[-2])
    cel2 = int(settings[-1])
    row_t = settings[4]
    num1 = numberOfXpath(row_t,settings[3])
    list1 = GetCustomValue(settings[3],num1,cel1,cel2)
    options = webdriver.ChromeOptions()
    options.add_argument('--args --disable-web-security')
    options.add_argument('--start-maximized')
    options.add_argument('--incognito')
    options.add_argument('--lang=zh-CN')
    options.add_argument('disable-infobars')
    options.add_experimental_option('useAutomationExtension', False)
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    options.add_argument("--start-maximized")
    driver = webdriver.Chrome(options=options)
    pmlogin(driver,user)
    for i in list1:
        print(i)
        wins = driver.window_handles
        customInput(driver,wins,i)
